Setting up the Foreign Key Constraint

Takeaways

  • db.relationship does not set up foreign key constraints for you. We need to add a column, some_parent_id, on the child model that has a foreign key constraint
  • Whereas we set db.relationship on the parent model, we set the foreign key constraint on the child model.
  • A foreign key constraint prefers referential integrity from one table to another, by ensuring that the foreign key column always maps a primary key in the foreign table.

db.ForeignKey question

db.ForeignKey

  • Option in db.column to specify a foreign key constraint, referring to the primary key of the other table / model
  • Gets defined on the Child model

Question 1 of 4

True/False: db.relationship sets up foreign keys

Question 2 of 4

On which model do we define each of the following?

Child Model

Parent Model

SQLAlchemy concept

Model

db.relationship

db.ForeignKey

Question 3 of 4

db.ForeignKey is passed into...

Question 4 of 4

Choose the correct option to fill in the <BLANK> to set up the foreign key constraint between these two models:

class School(db.Model):
  __tablename__ = 'schools'
  id = db.Column(db.Integer, primary_key=True)
  # ...

class Teacher(db.Model):
  __tablename__ = 'teachers'
  id = db.Column(db.Integer, primary_key=True)
  name = #...
  school_id = db.Column(db.Integer, <BLANK>)

Now let's apply what we learned to an example

Write out the Driver and Vehicle models

Please wait Loading…
No Open Files
OPEN FILE
No Open Terminals
NEW TERMINAL
Menu
full screen

Expand

Did you get it right?

Watch the next video to find out!